//
// Created by Champrin on 2022/10/28.
// 仅用作桂林电子科技大学2023赛季Evolution战队视觉组培训使用
//
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>

//颜色识别
int dcawcd() {
    cv::VideoCapture video(0);//打开摄像头
    cv::Mat frame;//每帧图像保存到的Mat
    cv::Mat channels[3];//frame的三个通道
    cv::Mat B, G, R;//BGR单独提取

    cv::Mat element = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3)); //腐蚀膨胀结构
    cv::Mat kernel = cv::getStructuringElement(0, cv::Size(3, 3)); //形态学运算结构

    cv::Mat RThreshold, BThreshold, GThreshold;//三个通道二值化
    cv::Mat RThreshold_MorphologyEx, BThreshold_MorphologyEx, GThreshold_MorphologyEx;//三个通道二值化后形态学操作

    while (true) {
        video >> frame;
        if (frame.empty())
            break;
        split(frame, channels);//分离色彩通道
        cv::imshow("B", channels[0]);
        cv::imshow("G", channels[1]);
        cv::imshow("R", channels[2]);

        R = channels[2] - channels[0];//BGR单独提取
        B = channels[0] - channels[2];
        G = channels[1] - channels[0];

        threshold(R, RThreshold, 90, 255, cv::THRESH_BINARY);//二值化
        morphologyEx(RThreshold, RThreshold_MorphologyEx, cv::MORPH_OPEN, kernel);//开运算
        morphologyEx(RThreshold_MorphologyEx, RThreshold_MorphologyEx, cv::MORPH_CLOSE, kernel);//闭运算

        threshold(B, BThreshold, 90, 255, cv::THRESH_BINARY);//二值化
        morphologyEx(BThreshold, BThreshold_MorphologyEx, cv::MORPH_OPEN, kernel);//开运算
        morphologyEx(BThreshold_MorphologyEx, BThreshold_MorphologyEx, cv::MORPH_CLOSE, kernel);//闭运算

        threshold(G, GThreshold, 90, 255, cv::THRESH_BINARY);//二值化
        morphologyEx(GThreshold, GThreshold_MorphologyEx, cv::MORPH_OPEN, kernel);//开运算
        morphologyEx(GThreshold_MorphologyEx, GThreshold_MorphologyEx, cv::MORPH_CLOSE, kernel);//闭运算

        cv::imshow("BThreshold", BThreshold);
        cv::imshow("RThreshold", RThreshold);
        cv::imshow("GThreshold", GThreshold);

        cv::imshow("BThreshold_MorphologyEx", BThreshold_MorphologyEx);
        cv::imshow("RThreshold_MorphologyEx", RThreshold_MorphologyEx);
        cv::imshow("GThreshold_MorphologyEx", GThreshold_MorphologyEx);

        cv::imshow("video", frame);
        if (cv::waitKey(1) == 27) //按帧率进行视频播放
            return 0;
    }
    return 0;
}
